package com.lm.security.controller;

import com.lm.security.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author lm_jcf
 * @date 2018/4/26 17:20
 */
@RestController
@RequestMapping("/file")
public class FileController {

    String folder = "D:\\resources\\codes\\lm-security\\lm-security-demo\\src\\main\\java\\com\\lm\\security\\controller";
    @PostMapping()
    public FileInfo update(MultipartFile file) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());



        File localFile = new File(folder, new Date().getTime() + ".txt");

//        file.getInputStream()
        file.transferTo(localFile);


        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void downLoad(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //jdk 1.7 写法，此写法可以使IO流自动关闭，不必写关闭代码块
        try (
                InputStream in = new FileInputStream(new File(folder, id+".txt"));
                OutputStream outputStream = response.getOutputStream();
                    ){
                response.setContentType("application/x-download");
                response.addHeader("Content-Disposition", "attachment;filename=test.txt");

                IOUtils.copy(in,outputStream);
                outputStream.flush();
            }

    }
}
